package cn.touna.jss.modules.third.bairong;

import cn.touna.risk.api.contraints.facet.First;
import cn.touna.risk.api.enums.SystemErrorCodeEnum;
import cn.touna.jss.common.enums.BaiRongResultEnum;
import cn.touna.jss.common.factory.ResponseFactory;
import cn.touna.jss.common.properties.disconf.BairongProperties;
import cn.touna.jss.common.util.ValidUtil;
import cn.touna.jss.modules.adapter.ApiMapping;
import cn.touna.jss.modules.third.bairong.entity.BaiRongEntity;
import cn.touna.jss.modules.third.bairong.util.BairongServiceHandler;
import cn.touna.jss.modules.third.jxl.JuXinLiService;
import cn.touna.jss.modules.third.jxl.entity.JuXinLiRequestEntity;
import cn.touna.risk.api.domain.Response;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 百融
 */

@Service
public class BairongService {

    private static final Logger logger = LogManager.getLogger(BairongService.class);

    @Autowired
    private BairongServiceHandler bairongServiceHandler;

    @Autowired
    private JuXinLiService juXinLiService;

    @Autowired
    private BairongProperties bairongConfig;

    /**
     * 特殊名单核查
     * @param baiRongEntity
     * @return
     */
    @ApiMapping(value="BaiRong.specialList",desc="百融.特殊名单核查")
    public Response specialList(BaiRongEntity baiRongEntity) {
        ValidUtil.checkRequestParams(baiRongEntity, First.class);
        try {
            String result = bairongServiceHandler.queryHttpsData(bairongConfig.getSpecialList(), bairongConfig.getHuaxiangUrl(), baiRongEntity);
            logger.info("specialList result ：{}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (result == null || jsonObject == null) {
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL, BaiRongResultEnum.analysisException.value());
            }
            String code = (String) jsonObject.get("code");
            if (code != null && !code.equals(BaiRongResultEnum.success.value()) && !code.equals(BaiRongResultEnum.matchIsEmpty.value())) {
                String resultMsg = BaiRongResultEnum.getValue(code);
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL, resultMsg);
            }
            return ResponseFactory.success(result);
        } catch (Exception e) {
            logger.error("Bairong specialList is exception", e);
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR, e.getMessage());
        }
    }


    /**
     * 多次申请核查（月度版）
     * @param request
     * @return
     */
    @ApiMapping(value="BaiRong.loanApplications",desc="百融.多次申请核查")
    public Response loanApplications(BaiRongEntity request) {
        String subApp ="ApplyLoanStr";
        return loanApplications(request,subApp);
    }

    /**
     * 多次申请核查(累计版)
     * @param request
     * @return
     */
    @ApiMapping(value="BaiRong.applyLoanStr",desc="百融.多次申请核查(累计版)")
    public Response applyLoanStr(BaiRongEntity request){
        Response response = ValidUtil.valid(request,First.class);
        if(response != null)
            return response;
        //meal代表产品，ApplyLoanStr代表累计版
        String meal = "ApplyLoanStr";
        return loanApplications(request,meal);
//        return loanApplications(request,subApp);
//        return  bairongServiceHandler.queryBatchData(meal,request);
    }


    /**
     * 多次申请核查
     * @param request
     * @param subApp
     * @return
     */
    private Response loanApplications(BaiRongEntity request,String subApp){
        Response response = ValidUtil.valid(request,First.class);
        if(response != null)
            return response;
        try {
            String result = bairongServiceHandler.queryHttpsData(subApp, bairongConfig.getHuaxiangUrl(), request);
            logger.info("loanApplications  result ：{}", result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (result == null || jsonObject == null) {
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL, BaiRongResultEnum.analysisException.value());
            }
            String code = (String) jsonObject.get("code");
            if (code != null && !code.equals(BaiRongResultEnum.success.value()) && !code.equals(BaiRongResultEnum.matchIsEmpty.value())) {
                String resultMsg = BaiRongResultEnum.getValue(code);
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL, resultMsg);
            }
            return ResponseFactory.success(result);
        } catch (Exception e) {
            logger.error("Bairong loanApplications is exception", e);
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_ERROR, e.getMessage());
        }
    }


    /**
     * 法院被执行人
     * @param baiRongEntity
     * @return
     */
    @ApiMapping(value="BaiRong.courtExecution",desc="百融.法院被执行人")
    public Response courtExecution(BaiRongEntity baiRongEntity) {
        return  bairongServiceHandler.queryBatchData(bairongConfig.getCourtExecution(), baiRongEntity);
//        try {
//            String result = bairongServiceHandler.queryBatchData(bairongConfig.getCourtExecution(), baiRongEntity);
//            logger.info("Bairong courtExecution  result ：{}", result);
//            return ResponseFactory.success(result);
//        } catch (Exception e) {
//            logger.error("Bairong courtExecution", e);
//            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
//        }
    }

    /**
     * 手机三要素
     *
     * @param baiRongEntity
     * @return
     */
    @ApiMapping(value="BaiRong.mobileCheck",desc="百融.手机三要素")
    public Response mobileCheck(BaiRongEntity baiRongEntity) {
        try {
            String result = bairongServiceHandler.querySingleData(bairongConfig.getMobileCheck(), baiRongEntity);
            logger.info("Bairong mobileCheck  result ：{}", result);
            return ResponseFactory.success(result);
        } catch (Exception e) {
            logger.error("Bairong mobileCheck", e);
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
        }
    }

    /**
     * 手机在网时长
     *
     * @param baiRongEntity
     * @return
     */
    @ApiMapping(value="BaiRong.mobileOnlineDuration",desc="百融.手机在网时长")
    public Response mobileOnlineDuration(BaiRongEntity baiRongEntity) {

        try {
            String result = bairongServiceHandler.querySingleData(bairongConfig.getMobileOnlineDuration(), baiRongEntity);
            logger.info("Bairong mobileOnlineDuration  result ：{}", result);
            return ResponseFactory.success(result);
        } catch (Exception e) {
            logger.error("Bairong mobileOnlineDuration", e);
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
        }
    }

    /**
     * 手机在网状态
     *
     * @param baiRongEntity
     * @return
     */
    @ApiMapping(value="BaiRong.mobileOnlineStatus",desc="百融.手机在网状态")
    public Response mobileOnlineStatus(BaiRongEntity baiRongEntity) {
        try {
            String result = bairongServiceHandler.querySingleData(bairongConfig.getMobileOnlineStatus(), baiRongEntity);
            logger.info("Bairong mobileOnlineDuration  result ：{}", result);
            return ResponseFactory.success(result);
        } catch (Exception e) {
            logger.error("Bairong mobileOnlineStatus", e);
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
        }
    }

    /**
     * 学历查询标准版
     *
     * @param baiRongEntity
     * @return
     */
    @ApiMapping(value="BaiRong.findEducation",desc="百融.学历查询标准版")
    public Response findEducation(BaiRongEntity baiRongEntity) {
        try {
            baiRongEntity.setFriendMobilePhone(null);
            String result = bairongServiceHandler.queryHttpsData(bairongConfig.getEducation(), bairongConfig.getHainaUrl(), baiRongEntity);
            logger.info("Bairong findEducation  result ：{}", result);
//            ThreadPoolUtil.submit(JssConstant.JSS_POOL_NAME, this, "accessJxlMiguan", baiRongEntity);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (result == null || jsonObject == null) {
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL, BaiRongResultEnum.analysisException.value());
            }
            String code = String.valueOf(jsonObject.get("code"));
            if (code != null && !code.equals(BaiRongResultEnum.haina_success.value())) {
                String resultMsg = BaiRongResultEnum.getValue(code) + "(" + result + ")";
                return ResponseFactory.fail(SystemErrorCodeEnum.JSS_EXTSYSTEM_RESP_FAIL, resultMsg);
            }
            return ResponseFactory.success(result);
        } catch (Exception e) {
            logger.error("Bairong education", e);
            return ResponseFactory.fail(SystemErrorCodeEnum.JSS_CALL_EXTSYSTEM_ERROR, e.getMessage());
        }
    }

    /**
     * 异步触发聚信立蜜罐
     *
     * @param identityEntity
     */
    private void accessJxlMiguan(BaiRongEntity baiRongEntity) {
        JuXinLiRequestEntity juXinLiRequestEntity = new JuXinLiRequestEntity();
        BeanUtils.copyProperties(baiRongEntity, juXinLiRequestEntity);
        juXinLiService.getMiguanData(juXinLiRequestEntity);
    }

}

